//
//  NRWHomeVC.m
//  NRWMall
//
//  Created by 邢毅 on 2018/5/11.
//  Copyright © 2018年 com.anpxd. All rights reserved.
//

#import "NRWHomeVC.h"
#import <SDCycleScrollView.h>
#import "NRWHomeHeaderView.h"
#import "NRWHotCarBrandRequest.h"
#import "NRWCarBrandModel.h"
#import "NRWCarListCell.h"
#import "NRWBrandSeriesVC.h"
#import "NRWBuyCarListRectModel.h"
#import "NRWBuyCarListApi.h"
#import "NRWBuyCarConditionModel.h"
#import "NRWSubscribeVC.h"
#import "NRWCarDetailVC.h"
#import "NRWLoginVC.h"
#import "NRWRotationListApi.h"
#import "NRWRotationListModel.h"
#import "NRWWebViewController.h"

typedef NS_ENUM(NSUInteger, NRWHeaderChannelType) {
    NRWHeaderChannelTypeNewCars,
    NRWHeaderChannelTypeIsAuth,
};

@interface NRWHomeVC ()
<UITableViewDelegate,
UITableViewDataSource,
SDCycleScrollViewDelegate,
NRWHomeHeaderViewDelegate,
NRWBrandSeriesVCDelegate>

@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NRWHotCarBrandRequest *hotBrandRequset;

@property (strong, nonatomic) NRWHomeHeaderView *header;

@property (strong, nonatomic) NSArray<NRWBuyCarListRectModel *> *carListModel;

@property (strong, nonatomic) NRWBuyCarListApi *carListApi;

@property (strong, nonatomic) NRWRotationListApi *rotationListApi;

@end

@implementation NRWHomeVC

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationView.title = @"首页";
    
    self.carListApi.params.carAuthState = nil;//设置为最新车源
    self.carListApi.params.orderColunm = @"CAR_SALE_TIME";
    self.carListApi.params.orderMode = @"DESC";
    
    [self setupUI];
    
    [self loadNewData];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

#pragma mark - setupUI
- (void)setupUI {

    self.navigationView.alpha = 0;
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH(), SCREEN_HEIGHT() - getTabBarHeight());
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView addHeaderRefreshWithTarget:self action:@selector(loadNewData)];
    self.tableView.mj_header.ignoredScrollViewContentInsetTop = -20;
    [self.tableView registerClass:[NRWCarListCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.tableFooterView = DPView();
    [self.view addSubview:self.tableView];

    self.header = [[NRWHomeHeaderView alloc] init];
    _header.frame = CGRectMake(0, 0, SCREEN_WIDTH(), 317 + getAdaptationWidth(160));
    _header.delegate = self;
    self.tableView.tableHeaderView = _header;
    
    UIButton *subscribeBtn = [[UIButton alloc] init];
    [subscribeBtn setImage:getImage(@"home_subscribe") forState:UIControlStateNormal];
    [subscribeBtn addTarget:self action:@selector(subscribeBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    subscribeBtn.frame = CGRectMake(SCREEN_WIDTH() - 75 - 12, SCREEN_HEIGHT() - getTabBarHeight() - 75 - 32, 75, 75);
    [self.view addSubview:subscribeBtn];
    [self.view bringSubviewToFront:subscribeBtn];
    
    UILabel *footLabel = [[UILabel alloc] init];
    footLabel.frame = CGRectMake(0, 0, SCREEN_WIDTH(), 40);
    footLabel.text = @"查看更多车源";
    footLabel.textColor = subFontColor();
    footLabel.font = getThemeFont(13);
    footLabel.textAlignment = NSTextAlignmentCenter;
    footLabel.userInteractionEnabled = YES;
    self.tableView.tableFooterView = footLabel;
    
    MJWeakSelf
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [footLabel addGestureRecognizer:tap];
    [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        NRWBuyCarConditionModel *model = [[NRWBuyCarConditionModel alloc] init];
        if ([weakSelf.carListApi.params.carAuthState isEqualToString:@"0"]) {//最新车源
            model.isCarAuthState = NO;
            model.sortModel.sortName = @"最新发布";
        } else {
            model.isCarAuthState = YES;
            model.sortModel.sortName = @"默认排序";
        }
        [weakSelf gotoBuyCarVCWithModel:model];
    }];
}

#pragma mark - privateMethod
- (void)loadNewData {
    
    [SVProgressHUD show];
    
    [self.hotBrandRequset startWithoutCache];
    
    [self.carListApi startWithoutCache];
	
	[self.rotationListApi startWithoutCache];
    
    [self.tableView endRefresh];
}

- (void)gotoBuyCarVCWithModel:(NRWBuyCarConditionModel *)model {
    
    UINavigationController *nav = self.tabBarController.viewControllers[1];
    if ([nav.topViewController isKindOfClass:NSClassFromString(@"NRWBuyCarVC")]) {
        [nav.topViewController setValue:model forKey:@"conditionModel"];
        [nav.topViewController setValue:@1 forKey:@"isNeedReloadData"];
        self.tabBarController.selectedIndex = 1;
    }
}

#pragma mark NetWork
- (void)requestFinished:(__kindof YTKBaseRequest *)request {
	
	if ([request.responseObject[@"code"] integerValue] == 0) {
		[NRWMessageHUD showMessage:request.responseObject[@"msg"] forTime:1.5 withRemindId:remindFail];
		return;
	}
    
    [SVProgressHUD dismiss];
    
    if (request == self.hotBrandRequset) {
        
        NRWCarBrandModel *model = [NRWCarBrandModel mj_objectWithKeyValues:request.responseObject];
        if (model.result.count > 7) {
            model.result = [model.result subarrayWithRange:NSMakeRange(0, 7)];
            _header.hotCarModel = model;
        } else if (model.result.count < 7) {
            [NRWMessageHUD showMessage:@"请求出错" forTime:1.5 withRemindId:remindFail];
        } else if (model.result.count == 7) {
            _header.hotCarModel = model;
        }
    }
    
    if (request == self.carListApi) {
        
		NRWBuyCarListDataModel *model = [NRWBuyCarListDataModel mj_objectWithKeyValues:self.carListApi.responseObject];
		NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:model.result.count];
		for (Result *itemModel in model.result) {
			NRWBuyCarListRectModel *rectModel = [[NRWBuyCarListRectModel alloc] init];
			rectModel.dataModel = itemModel;
			[arrM addObject:rectModel];
		}
		self.carListModel = arrM.copy;
		[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    }
	
	if (request == self.rotationListApi) {
		
		self.header.rotationListModel = [NRWRotationListModel mj_objectWithKeyValues:self.rotationListApi.responseObject];
	}
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request {
    
    [NRWMessageHUD showMessage:@"服务器繁忙, 请稍后再试" forTime:1.5 withRemindId:remindFail];
}

#pragma mark touchEvent
- (void)subscribeBtnDidClick:(UIButton *)sender {
    
    if ([NRWUserInfoModel shared].isLogin) {
        
        NRWSubscribeVC *vc = [[NRWSubscribeVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        
        MJWeakSelf
        NRWLoginView *loginView = [[NRWLoginView alloc] init];
        loginView.loginSuccessBlock = ^{
            NRWSubscribeVC *vc = [[NRWSubscribeVC alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        [loginView show];
    }
}

#pragma mark - publicMethod

#pragma mark - DelegateMethod
#pragma UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.carListModel.count > 10) {
        return 10;
    } else {
        return self.carListModel.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NRWCarListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
	cell.carFrameModel = self.carListModel[indexPath.row];
	
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NRWCarDetailVC *vc = [[NRWCarDetailVC alloc] init];
    vc.thisCarModel = self.carListModel[indexPath.row].dataModel;
    vc.carId = self.carListModel[indexPath.row].dataModel.carId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (160 < self.tableView.contentOffset.y) {
        return;
    }
    
    if (self.tableView.contentOffset.y < 0) {
        self.navigationView.alpha = 0;
    }
    
    self.navigationView.alpha = self.tableView.contentOffset.y / (160.0 - getNavHeight());
}

#pragma mark NRWHomeHeaderViewDelegate
- (void)homeHeaderView:(NRWHomeHeaderView *)view carCategoryDidClickWithTag:(CarCategotyViewClick)tag {
    
    NRWBuyCarConditionModel *model = [[NRWBuyCarConditionModel alloc] init];
    
    if (tag == CarCategotyViewClickPreferred) {
    
        model.isCarAuthState = YES;
    
    } else if (tag == CarCategotyViewClickNewCar) {
        
        model.filterModel.mileageTo = @"3";
        model.filterModel.mileageFirstIndex = 0;
        model.filterModel.mileageLastIndex = 2;
        model.filterModel.carAgeTo = @"1";
        model.filterModel.carAgeFirstIndex = 0;
        model.filterModel.carAgeLastIndex = 1;
        model.filterModel.mileageTitle = @"0-3万公里";
        model.filterModel.carAgeTitle = @"1年以内";
    } else if (tag == CarCategotyViewClickExercise) {
        
        model.priceModel.priceTo = @"5";
        model.priceModel.priceTitle = @"0-5万";
    } else if (tag == CarCategotyViewClickSUV) {
        
        model.filterModel.carTypeId = @"9";
        model.filterModel.carTypeName = @"精选SUV";
    } else if (tag == CarCategotyViewClickCar) {
        
        model.filterModel.carTypeId = @"2";
        model.filterModel.carTypeName = @"时尚轿车";
    } else if (tag == CarCategotyViewClickSportsCar) {
        
        model.filterModel.carTypeId = @"13";
        model.filterModel.carTypeName = @"跑车";
    }
    
        [self gotoBuyCarVCWithModel:model];
}

- (void)homeHeaderView:(NRWHomeHeaderView *)view hotCarBrandDidClickAtIndex:(NSInteger)index {
    
    if (index == 7) {
        NRWBrandSeriesVC *vc = [[NRWBrandSeriesVC alloc] init];
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        
        NRWBuyCarConditionModel *model = [[NRWBuyCarConditionModel alloc] init];
        model.brandModel.brandName = _header.hotCarModel.result[index].fastBrandName;
        model.brandModel.brandId = _header.hotCarModel.result[index].fastBrandId;
        
        [self gotoBuyCarVCWithModel:model];
    }
}

- (void)homeHeaderView:(NRWHomeHeaderView *)view channelDidClickAtIndex:(NSInteger)index {
    
    if (index == 0) {
        
        self.carListApi.params.carAuthState = @"10";
        self.carListApi.params.orderColunm = nil;
        self.carListApi.params.orderMode = nil;
    } else if (index == 2) {
        
        self.carListApi.params.carAuthState = @"0";
        self.carListApi.params.orderColunm = @"CAR_SALE_TIME";
        self.carListApi.params.orderMode = @"DESC";
    }
    
    [self.carListApi start];
}

- (void)homeBannerView:(NRWHomeHeaderView *)view bannerDidClickAtIndex:(NSInteger)index {
	
	NSString *url = self.header.rotationListModel.result[index].rotationUrl;
	
	if (isEmptyString(url)) {
		return;
	}
	
	NRWWebViewController *vc = [[NRWWebViewController alloc] init];
	vc.url = url;
	[self.navigationController pushViewController:vc animated:YES];
}

- (void)brandSeriesVC:(NRWBrandSeriesVC *)view selectBrandId:(NSString *)selectBrandId selectBrandName:(NSString *)selectBrandName selectSeriesId:(NSString *)selectSeriesId selectSeriesName:(NSString *)selectSeriesName {
    
    NRWBuyCarConditionModel *model = [[NRWBuyCarConditionModel alloc] init];
    model.brandModel.brandId = selectBrandId;
    model.brandModel.brandName = selectBrandName;
    model.brandModel.seriesId = selectSeriesId;
    model.brandModel.seriesName = selectSeriesName;
    
    [self gotoBuyCarVCWithModel:model];
}

#pragma mark - touchEventAction

#pragma mark - setter

#pragma mark - getter
- (NRWHotCarBrandRequest *)hotBrandRequset {
    
    if (_hotBrandRequset == nil) {
        _hotBrandRequset = [[NRWHotCarBrandRequest alloc] init];
        _hotBrandRequset.delegate = self;
    }
    return _hotBrandRequset;
}

- (NRWBuyCarListApi *)carListApi {
    
    if (_carListApi == nil) {
        _carListApi = [[NRWBuyCarListApi alloc] init];
        _carListApi.delegate = self;
        _carListApi.needCache = YES;
    }
    return _carListApi;
}

- (NRWRotationListApi *)rotationListApi {
	
	if (_rotationListApi == nil) {
		_rotationListApi = [NRWRotationListApi requestWithDelegate:self];
	}
	return _rotationListApi;
}

@end
